<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\Order as OrderModel;
use app\common\controller\Backend;
use app\common\model\Room as RoomModel;
use app\common\model\User as UserModel;
use think\Request;

class Order extends Backend
{
    //订单列表
    public function index(Request $request)
    {
        $roomList = RoomModel::select()->toArray();
        $userList = UserModel::select()->toArray();
        $roomIdMap = array_column($roomList, 'name', 'id');
        $userIdMap = array_column($userList, 'username', 'id');

        $orderList = OrderModel::select()->toArray();
        foreach ($orderList as &$order) {
            $order['room_name'] = $roomIdMap[$order['room_id']] ?? '';
            $order['username'] = $userIdMap[$order['user_id']] ?? '';
            if ($order['status'] == 1) {
                $order['status_str'] = '已预订';
            } else if ($order['status'] == 2) {
                $order['status_str'] = '退房审核中';
            } else if ($order['status'] == 3) {
                $order['status_str'] = '已取消';
            } else if ($order['status'] == 4) {
                $order['status_str'] = '入住中';
            } else if ($order['status'] == 5) {
                $order['status_str'] = '已退房';
            }
        }

        if (!empty($orderNo = $request->get('order_no'))) {
            $orderList = array_filter($orderList, function ($item) use ($orderNo) {
                return str_contains($item['order_no'], $orderNo);
            });
        }

        return $this->fetch('order/index', ['orderList' => $orderList]);
    }

    //订单保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();

            if ($data['status'] == 1) {
                $data['status'] = 4;
            } else if ($data['status'] == 4) {
                $data['status'] = 5;
            }
            if (empty($data['id'])) {
                OrderModel::create($data);
            } else {
                OrderModel::update($data);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }

    //订单删除
    public function delete(Request $request)
    {
        try {
            OrderModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }

    //订单编辑
    public function edit(Request $request)
    {
        $order = OrderModel::findOrEmpty($request->get('id', 0));
        $room = RoomModel::find($order['room_id']);
        $user = UserModel::find($order['user_id']);
        $order['room_name'] = $room['name'] ?? '';
        $order['username'] = $user['username'] ?? '';
        return $this->fetch('order/edit', [
            'order' => $order
        ]);
    }
}
